/**
 *  Copyright (c) 2017-2022 Rushang Co.Ltd All Rights Reserved.
 */
package com.rshang.rsdp.config;

import java.io.IOException;
import java.util.Locale;
import java.util.Properties;

import org.beetl.core.resource.WebAppResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.rshang.rsdp.mapper.interceptor.SessionHandlerInterceptor;

/**
 * 功能简介：spring bean主配置类<br/>
 * @author zhangjun
 * @create 2017年7月19日下午3:53:08
 * 
 */
@Configuration
@EnableCaching
public class RsdpWebConfig extends WebMvcConfigurerAdapter {

    /**
     * beetl配置
     * @return	BeetlGroupUtilConfiguration
     */
	@Bean(initMethod = "init", name = "beetlConfig")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
 
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
      try {
			String root =  patternResolver.getResource("classpath:templates").getFile().toString();
			WebAppResourceLoader webAppResourceLoader = new WebAppResourceLoader(root);
	        beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader);
	 
	        beetlGroupUtilConfiguration.setConfigFileResource(patternResolver.getResource("classpath:beetl.properties"));
	        return beetlGroupUtilConfiguration;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
        
    }

    /**
     * beetl配置
     * @param beetlGroupUtilConfiguration
     * @return	BeetlSpringViewResolver
     */
    @Bean(name = "beetlViewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
            BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
            beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
            beetlSpringViewResolver.setOrder(0);
            beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
            beetlSpringViewResolver.setSuffix(".html");
            //beetlSpringViewResolver.setPrefix(templatesPath);
            return beetlSpringViewResolver;
    }
    
    /**
	 * 创建ObjectMapper bean
	 * @return
	 * 		ObjectMapper
	 */
	@Bean
	public ObjectMapper createObjectMapper(@Autowired JsonSerializer<Object> jsonSerializer)
	{
		ObjectMapper mapper = new ObjectMapper();
		//设置null为空字符串
		mapper.getSerializerProvider().setNullValueSerializer(jsonSerializer);
		return mapper;
	}
	
	/**
	 * 自定义jackson消息转换 空值转换为null
	 * @return
	 * 		MappingJackson2HttpMessageConverter
	 */
	@Bean 
	public MappingJackson2HttpMessageConverter createConvert(@Autowired ObjectMapper mapper)
	{
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		converter.setObjectMapper(mapper);
		return converter;
	}
	/**
	 * 设置默认Locale
	 * @return
	 * 		LocaleResolver
	 */
	@Bean("localeResolver")
    public LocaleResolver localeResolver() {  
        SessionLocaleResolver slr = new SessionLocaleResolver();  
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);  
        return slr;  
    }  
	
	/**
	 * i18n国际化
	 * @return
	 * 		ReloadableResourceBundleMessageSource
	 */
	@Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        String[] resources = {"classpath:i18n/messages"};
        messageSource.setBasenames(resources);
        messageSource.setCacheSeconds(-1);
        return messageSource;
    }

	/**
	 * ehcache缓存管理器bean
	 */
	@Bean
    public EhCacheManagerFactoryBean createEhCacheManagerFactoryBean(){
		EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
		factoryBean.setShared(true);
		factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
		return factoryBean;
    }
	/**
	 * ehcache缓存管理器
	 */
	@Bean
    public EhCacheCacheManager createEhCacheCacheManager(@Autowired EhCacheManagerFactoryBean bean){
		return new EhCacheCacheManager(bean.getObject());
    }
	
	/**
	 * 验证码生成器
	 */
	@Bean
	public DefaultKaptcha captchaProducer(){
		DefaultKaptcha captchaProducer =new DefaultKaptcha();
		Properties properties =new Properties();
		properties.setProperty("kaptcha.border","yes");
		properties.setProperty("kaptcha.border.color","204,203,155");
		properties.setProperty("kaptcha.textproducer.font.color","248,16,0");
		properties.setProperty("kaptcha.image.width","150");
		properties.setProperty("kaptcha.image.height","40");
		properties.setProperty("kaptcha.textproducer.font.size","32");
		properties.setProperty("kaptcha.session.key",Constants.KAPTCHA_SESSION_KEY);
		properties.setProperty("kaptcha.textproducer.char.length","4");
		properties.setProperty("kaptcha.textproducer.char.space","5");
		properties.setProperty("kaptcha.noise.color","50,105,168");
		//properties.setProperty("kaptcha.textproducer.font.names","微软雅黑,宋体,楷体");
		Config config=new Config(properties);
		captchaProducer.setConfig(config);
		return  captchaProducer;
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new SessionHandlerInterceptor());
		super.addInterceptors(registry);
	}
	
	/**
	 * 初始化文件上传处理器
	 * @return MultipartResolver
	 */
	/*@Bean
	public MultipartResolver multipartResolver() {
	    return new StandardServletMultipartResolver();
	}*/
}
